package com.example.network.retrofit

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.network.databinding.ActivityRetrofitBinding
import com.example.network.model.App
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.HttpURLConnection
import kotlin.concurrent.thread

class RetrofitActivity : AppCompatActivity() {
    private lateinit var binding: ActivityRetrofitBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRetrofitBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        request()
    }

    private fun request() {
        thread {
            val mocker = ServerMocker()

            /**
             * 绑定服务器地址
             */
            val retrofit = Retrofit.Builder()
                .baseUrl(mocker.url)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
            val appService = retrofit.create(AppService::class.java)

            appService.getAppData().enqueue(object : Callback<List<App>> {
                override fun onResponse(
                    call: Call<List<App>>,
                    response: Response<List<App>>
                ) {
                    val buffer = StringBuilder()
                    val list = response.body()
                    if (list != null) {
                        for (app in list) {
                            buffer.append("${app.id} ${app.name} ${app.version}\n")
                        }
                    }

                    showResponse(buffer.toString())
                }

                override fun onFailure(call: Call<List<App>>, t: Throwable) {
                    t.printStackTrace()
                }
            })
        }

    }

    private fun showResponse(response: String) {
        binding.responseText.text = response
    }
}